import React from 'react';
import { observable, action, toJS } from 'mobx';
import {inject, observer} from 'mobx-react';
import {Row, Col, Input, Tabs, Button, Alert, Spin, Icon, Form, InputNumber, Modal, message} from 'antd'
import { WeaForm, WeaSwitch,WeaTableNew } from 'comsMobx';
import {
    WeaLocaleProvider,
    WeaErrorPage,
    WeaAlertPage,
    WeaTop,
    WeaTab,
    WeaInput,
    WeaLeftRightLayout,
    WeaSearchGroup,
    WeaRightMenu,
    WeaInputSearch,
    WeaBrowser,
    WeaSelect,
    WeaDialog,
    WeaFormItem,
    WeaProgress,
    WeaTools
} from 'ecCom'

import '../../../workflow/util/windowFun';

const getLabel = WeaLocaleProvider.getLabel;
const confirm = Modal.confirm;
const WeaTable = WeaTableNew.WeaTable;
const ButtonGroup = Button.Group;

@inject('ManuallyDispatchStore')
@observer
class ManuallyDispatch extends React.Component {
    constructor(props) {
        super(props);
    }
    componentDidMount() {//一些初始化请求
        const { ManuallyDispatchStore } = this.props;
        //初始化列表
        ManuallyDispatchStore.doSearch();
        ManuallyDispatchStore.getRightMenu();
        ManuallyDispatchStore.getConditionInfo();
    }
    componentWillReceiveProps(nextProps) {
    }

    componentWillUnmount() {
        //组件卸载时一般清理一些状态
    }

    render() {
        const { ManuallyDispatchStore } = this.props;
        const { sessionkey, setShowSearchAd,loading , form,tableStore ,showSearchAd ,hasRight,setQuickSearchValue,dialogtitle,visible } = ManuallyDispatchStore;
        const footer=[
            <Button key="submit" type="primary" onClick={this.onSubmit.bind(this)}>
                {getLabel(725, "提 交")}
            </Button>]
        return (
            <div>

                {
                    !hasRight && <WeaAlertPage >
                        <div>
                            {getLabel(2012, '对不起，您暂时没有权限！')}
                        </div>
                    </WeaAlertPage>
                }{
                hasRight &&
                <WeaRightMenu datas={this.getRightMenu()}>
                    <WeaTop
                        title={getLabel(128468, "手动")+getLabel(128469, "派工")}
                        loading={loading}
                        icon={<i className='icon-coms-workflow'/>}
                        iconBgcolor={"#0079DE"}
                        buttons={this.getButtons()}
                        buttonSpace={10}
                        showDropIcon={true}
                        dropMenuDatas={this.getRightMenu()}
                    >
                        <WeaTab
                            buttonsAd={this.getTabButtonsAd()}
                            searchType={['base','advanced']}
                            searchsBaseValue={form.getFormParams()[this.quickSearchPara] || ''}
                            searchsAd={this.getSearchs()}
                            showSearchAd={showSearchAd}
                            setShowSearchAd={() => {setShowSearchAd(!showSearchAd);}}
                            hideSearchAd={()=>ManuallyDispatchStore.setShowSearchAd(false)}
                            onSearch={v=>ManuallyDispatchStore.doSearch({...form.getFormParams()})}
                            onSearchChange={value => {
                                form.updateFields({ [this.quickSearchPara]: { value } })
                                setQuickSearchValue(value);
                            }}
                        />
                        <WeaTable
                            loading={loading}
                            sessionkey={sessionkey}
                            comsWeaTableStore={tableStore}
                            hasOrder={true}
                            needScroll={true}
                            onOperatesClick={this.getOperatesClick1.bind(this)}
                        />
                    </WeaTop>

                    <WeaDialog
                        title={dialogtitle}
                        visible={visible}
                        buttons={footer}
                        moreBtn={{datas:this.getRightMenu1(),collectParams:{favname:dialogtitle, favouritetype:'2' ,importantlevel:'1'}}}
                        hasScroll={true}
                        icon="icon-coms-workflow"
                        iconBgcolor="#0079DE"
                        onCancel={this.closeDialog1.bind(this)}
                        zIndex={995}
                        style={{width: 500, height: 260}}
                    >
                        <WeaRightMenu datas={this.getRightMenu1()}>
                            {this.getItems1()}
                        </WeaRightMenu>
                    </WeaDialog>

                </WeaRightMenu>
            }
            </div>
        )
    }

    //页面右键
    getRightMenu() {
        const { ManuallyDispatchStore } = this.props;
        const { rightMenu, setVisible,tableStore,setRequestids } = ManuallyDispatchStore;
        const selectedRowKeys = tableStore.selectedRowKeys;
        let isDisabled = selectedRowKeys.length === 0 ;
        let btnArr = [];
        rightMenu.slice().forEach(m => {
            let onClick = () => {
            };
            if (m.menuFun.indexOf('batchDispatch()') >= 0) {
                onClick = () => {
                    setVisible(true);
                    let ids = selectedRowKeys.join();
                    setRequestids(ids);
                    ManuallyDispatchStore.setDialogType({dialogType:'batchDispatch',requestids:selectedRowKeys.join()});
                }
            }

            btnArr.push({
                key: m.type,
                icon: <i className={m.menuIcon}/>,
                content: m.menuName,
                disabled:m.isControl == '1' && isDisabled ,
                onClick,
            });
        });
        return btnArr;
    }

    //根据dialogtype获取弹出框右键
    getRightMenu1() {
        const { ManuallyDispatchStore } = this.props;
        const { chooseDialogRM1} = ManuallyDispatchStore;
        let btnArr = [];
        chooseDialogRM1.slice().forEach(m => {
            let onClick = () => {
            };
            if (m.menuFun.indexOf('onSubmit()') >= 0) {
                onClick = () => {
                    this.onSubmit();
                }
            }
            if (m.menuFun.indexOf('closeDialog1()') >= 0) {
                onClick = () => {
                    this.closeDialog1();
                }
            }

            btnArr.push({
                key: m.type,
                icon: <i className={m.menuIcon}/>,
                content: m.menuName,
                onClick,
            });
        });
        return btnArr;
    }

    //获取派工弹出框的内容
    getItems1() {
        const { ManuallyDispatchStore } = this.props;
        const { chooseDialogCon1,form1,chooseDialogCon2,form2 } = ManuallyDispatchStore;
        let items = [];
        let group = [];
        const {isFormInit} = form1;
        const formParams = form1.getFormParams();
        isFormInit && chooseDialogCon1.slice().map(c =>{
            c.items.map(fields => {
                items.push({
                    com:(<WeaFormItem
                        label={`${fields.label}`}
                        labelCol={{span: `${fields.labelcol}`}}
                        wrapperCol={{span: `${fields.fieldcol}`}}>
                        <WeaSwitch fieldConfig={fields} form={form1} formParams={formParams}/>
                    </WeaFormItem>),
                    colSpan:1
                });
            });
            group.push(<WeaSearchGroup col={1} needTigger={true} title={c.title} showGroup={true} items={items}/>)
        })
        return group;
    }

    //派工提交
    onSubmit(){
        const {ManuallyDispatchStore} = this.props;
        const {form1,setVisible,tableStore,requestids}=ManuallyDispatchStore;
        form1.validateForm().then(f=>{
            if(f.isValid){
                ManuallyDispatchStore.onSubmit({requestids:requestids,...form1.getFormParams()});
                ManuallyDispatchStore.form1.reset();
                setVisible(false);
            }else{
                f.showErrors();
                Modal.warning({
                    title: getLabel(15172, "系统提示"),
                    content: getLabel(383975, "必要信息不完整，红色标记为必填项！")
                });
            }
        })
    }

    //关闭规则设置弹出框
    closeDialog1(){
        const {ManuallyDispatchStore} = this.props;
        const {form1,setVisible,setRequestids}=ManuallyDispatchStore;
        setVisible(false);
        setRequestids("");
        form1.reset();
    }

    //高级搜索查询项
    getSearchs(){
        const { ManuallyDispatchStore } = this.props;
        const { conditioninfo,form } = ManuallyDispatchStore;
        const {isFormInit} = form;
        let group = [];
        const formParams = form.getFormParams();
        isFormInit && toJS(conditioninfo).map(c =>{
            let items = [];
            c.items.map(fields => {
                if (fields.isQuickSearch) {
                    this.quickSearchPara = fields.domkey[0];
                }
                items.push({
                    com:(<WeaFormItem
                        label={`${fields.label}`}
                        labelCol={{span: `${fields.labelcol}`}}
                        wrapperCol={{span: `${fields.fieldcol}`}}>
                        <WeaSwitch fieldConfig={fields} form={form} formParams={formParams}/>
                    </WeaFormItem>),
                    colSpan:1
                })
            });
            group.push(<WeaSearchGroup needTigger={true} title={c.title} showGroup={c.defaultshow} items={items}/>)
        });
        return group;

    }

    //高级搜索底部按钮
    getTabButtonsAd(){
        const { ManuallyDispatchStore } = this.props;
        const { form, doSearch, setShowSearchAd } = ManuallyDispatchStore;
        return [
            (<Button type="primary" onClick={()=>{
                ManuallyDispatchStore.doSearch({...form.getFormParams()});
                setShowSearchAd(false);
            }}>{getLabel(197, "搜索")}</Button>),
            (<Button type="ghost" onClick={() => form.reset()}>{getLabel(2022, "重置")}</Button>),
            (<Button type="ghost" onClick={() => {
                setShowSearchAd(false);
            }}>{getLabel(201, "取消")}</Button>)
        ]
    }

    //顶部右侧菜单
    getButtons() {
        const { ManuallyDispatchStore} = this.props;
        const { rightMenu,setVisible, tableStore,setRequestids} = ManuallyDispatchStore;
        const selectedRowKeys = tableStore.selectedRowKeys;
        let isDisabled = selectedRowKeys.length === 0 ;
        let btnArr = [];
        rightMenu.slice().forEach(m => {
            let onClick = () => {
            };
            let content = m.menuName;
            if (m.menuFun.indexOf('batchDispatch()') >= 0) {
                onClick = () => {
                    setVisible(true);
                    let ids = selectedRowKeys.join();
                    setRequestids(ids);
                    ManuallyDispatchStore.setDialogType({dialogType:'batchDispatch',requestids:ids});
                }
            }

            btnArr.push(<Button type="primary"
                                disabled={(m.isControl == '1' && isDisabled )}
                                onClick={onClick}>
                {content}
            </Button>);
        });
        return btnArr;
    }

    //分页组件操作菜单
    getOperatesClick1(record,index,operate,flag){
        const {ManuallyDispatchStore} = this.props;
        const {setVisible,setRequestids} = ManuallyDispatchStore;
        const funName = operate.href.replace(/(javascript\:)|(\(\))/g, () => '');
        if(funName.indexOf('onDispatch') >= 0) {
            let ids = record.requestid;
            setRequestids(ids);
            setVisible(true);
            ManuallyDispatchStore.setDialogType({dialogType:'onDispatch',requestids:ids});
        }
    }

}

//组件检错机制
class MyErrorHandler extends React.Component {
    render() {
        const hasErrorMsg = this.props.error && this.props.error !== "";
        return(
            <WeaErrorPage msg={ hasErrorMsg ? this.props.error : getLabel(384697, "对不起，该页面异常，请联系管理员！") } />
        );
    }
}



ManuallyDispatch = WeaTools.tryCatch( React, MyErrorHandler, { error: "" })(ManuallyDispatch);


export default ManuallyDispatch